package mygame;

import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.debug.WireBox;
import gameobject.construct.Construct;
import java.io.IOException;

/** A voxel represents a 3-dimensional box of space. */
public class Voxel implements Savable {
    public static final float VOXEL_EXTENT = 1.0f;
    public static final float VOXEL_DIAMETER = VOXEL_EXTENT * 2;
    protected Vector3i voxelGridLocation;
    protected Construct occupyingConstruct;
    protected Geometry wireframe; //for debugging
    
    public Voxel() {}

    public Voxel(Construct occupyingConstruct) {
	this.occupyingConstruct = occupyingConstruct;
    }
    
    public Voxel(Vector3i voxelGridLocation, Construct occupyingConstruct) {
	if(voxelGridLocation != null)
	    this.voxelGridLocation = voxelGridLocation.clone();
	this.occupyingConstruct = occupyingConstruct;
    }

    public Vector3i getVoxelGridLocation() {
	return voxelGridLocation;
    }

    public void setVoxelGridLocation(Vector3i voxelGridLocation) {
	this.voxelGridLocation = voxelGridLocation.clone();
    }

    public Construct getOccupyingConstruct() {
	return occupyingConstruct;
    }

    public void setOccupyingConstruct(Construct occupyingConstruct) {
	this.occupyingConstruct = occupyingConstruct;
    }
    
    @Override
    public String toString() {
        return "(" + voxelGridLocation + ", " + occupyingConstruct + ")";
    }

    public void write(JmeExporter ex) throws IOException {
	OutputCapsule capsule = ex.getCapsule(this);
        capsule.write(voxelGridLocation, "voxelGridLocation", Vector3i.ZERO);
        capsule.write(occupyingConstruct, "occupyingConstruct", null);
        capsule.write(wireframe, "wireframe", null);
    }

    public void read(JmeImporter im) throws IOException {
	InputCapsule capsule = im.getCapsule(this);
        voxelGridLocation = (Vector3i)capsule.readSavable("voxelGridLocation", Vector3i.ZERO);
        occupyingConstruct = (Construct)capsule.readSavable("occupyingConstruct", null);
        wireframe = (Geometry)capsule.readSavable("wireframe", null);
    }

    public Geometry getWireframe() {
	if(wireframe == null) {
	    wireframe = new Geometry("voxel wireframe", new WireBox(Voxel.VOXEL_EXTENT, Voxel.VOXEL_EXTENT, Voxel.VOXEL_EXTENT));
	    Material mat = new Material(DataStore.assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
	    mat.getAdditionalRenderState().setWireframe(true);
	    mat.setColor("Color", ColorRGBA.Magenta);
	    wireframe.setMaterial(mat);
	    wireframe.setLocalTranslation(VoxelGrid.getWorldLocation(getVoxelGridLocation()));
	}
	return wireframe;
    }
}
